package com.int_tech.rate.controller;

import com.int_tech.car.dao.CarDao;
import com.int_tech.car.entity.Car;
import com.int_tech.control.controller.contController;
import com.int_tech.control.dao.RateDao;
import com.int_tech.control.entity.Rate;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.mession.service.MessionService;
import com.int_tech.messionLog.dao.MessionLogDao;
import com.int_tech.messionLog.dao.MessionLogShowDao;
import com.int_tech.messionLog.entity.MessionLog;
import com.int_tech.messionLog.entity.MessionLogShow;
import com.int_tech.rate.entity.RateInfo;
import com.int_tech.utils.DateTool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by liubch on 2017/10/10.
 */
@Controller
@RequestMapping("rate")
public class RateController {

    @Autowired
    private MessionService messionService;

    @Autowired
    private RateDao rateDao;

    @Autowired
    private CarDao carDao;

    @Autowired
    private MessionLogDao messionLogDao;

    @Autowired
    private MessionDao messionDao;

    @Autowired
    private MessionLogShowDao messionLogShowDao;


    /**
     * 通过车牌号查询任务列表
     * @param request
     * @param carNumber
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getMessionByCarNumber", method= RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarsByStationId(HttpServletRequest request, String carNumber,String zhouQi) throws UnsupportedEncodingException, UnknownHostException, ParseException {

//        carNumber = "0"+carNumber;

//        Car cars = carDao.findByCarCnumber(carNumber);
        String today = DateTool.Date2String(new Date(),"yyyy-MM-dd");
//        String today = "2018-05-27";
        if(StringUtils.isEmpty(zhouQi))
        {
            zhouQi = "zhou";
        }

        String startTime = "";
        String endTime = "";

        if("zhou".equals(zhouQi))
        {
            String result = getFirstAndLastOfWeek(today);
            startTime = result.split("=")[0] + " 00:00:00";
            endTime = result.split("=")[1] + " 23:59:59";

        }
        else
        {
            String result = getFirstAndLastOfMonth();
            startTime = result.split("=")[0] + " 00:00:00";
            endTime = result.split("=")[1] + " 23:59:59";
        }

        Date sTime = DateTool.string2Date(startTime,"yyyy-MM-dd HH:mm:ss");
        Date eTime = DateTool.string2Date(endTime,"yyyy-MM-dd HH:mm:ss");

        //通过车牌号查询过往任务单号
        List<Mession> messionList = messionDao.findByCarNumberAndCreateTimeAndCheckStatusAndYiChangAndIsOver(carNumber,sTime,eTime,3,0,1);

        //查询车辆
        Car car = carDao.findCarByCarNumberAndIsDel(carNumber,0);

            List<RateInfo> rateInfos = new ArrayList<>();

        for (Mession mession : messionList)
        {
            //如果起点终点是一个，跳过
            String startAddress = mession.getStartAddress().substring(0,mession.getStartAddress().lastIndexOf("("));
            String endAddress = mession.getStartAddress().substring(0,mession.getEndAddress().lastIndexOf("("));

            /*if(startAddress.equals(endAddress))
            {
                continue;
            }*/

            if("010201802210068".equals(mession.getMessionNumber()))
            {
                System.out.print(111);
            }
            if(mession.getIsOver() == 0)
            {
                continue;
            }

            //装载率和任务暂时用车牌号关联
            RateInfo info = new RateInfo();
            info.setMessionId(mession.getId());
            info.setMessionsNumber(mession.getMessionNumber());
            info.setStartPlace(mession.getStartAddress());
            info.setEndPlace(mession.getEndAddress());

            //查询装载率
            Rate rate = rateDao.findByCarNumber(carNumber);


            try
            {
                //计算体积
                Double tj = (Double.parseDouble(car.getLength())*Double.parseDouble(car.getWidth())*Double.parseDouble(car.getHeight())*Double.parseDouble(mession.getRate()))/100;

                DecimalFormat df=new DecimalFormat(".#");
                String st=df.format(tj);

                info.setTiji(st);

                DecimalFormat format = new DecimalFormat("0.0");
                String a = format.format(new BigDecimal(mession.getRate()));
                info.setRateValue(a);


                //装车用时
                String zcdate = getDistanceTime(DateTool.Date2String(mession.getStartOpenDoorTime(),"yyyy-MM-dd HH:mm:ss"),DateTool.Date2String(mession.getStartCloseDoorTime(),"yyyy-MM-dd HH:mm:ss"));
                //卸车用时
                String xcdate = getDistanceTime(DateTool.Date2String(mession.getEndOpenDoorTime(),"yyyy-MM-dd HH:mm:ss"),DateTool.Date2String(mession.getEndCloseDoorTime(),"yyyy-MM-dd HH:mm:ss"));
                info.setOnTime(zcdate);
                info.setOfTime(xcdate);

                rateInfos.add(info);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        JSONArray jsonArray = JSONArray.fromObject(rateInfos);

        return jsonArray.toString();
    }



    /**
     * 通过messionId获取轨迹坐标点数组
     * @param request
     * @param messionId
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getMessionPotntByMessionId", method=RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getMessionPotntByMessionId(HttpServletRequest request, String messionId,String carNumber) throws UnsupportedEncodingException, UnknownHostException, ParseException {

//        List<MessionLog> messionLogList = messionLogDao.findMessionLogByMessionNumberOrderByCreateTimeDesc(messionId);

//        List<MessionLogShow> messionLogList = messionLogShowDao.findMessionLogByMessionNumberOrderByCreateTimeDesc(messionId);
        List<MessionLogShow> messionLogList = messionLogShowDao.findMessionLogByMessionNumberAndCarNumberOrderByCreateTimeDesc(messionId,carNumber);

        JSONArray jsonArray = JSONArray.fromObject(messionLogList);

        return jsonArray.toString();
    }

    /**
     * 获取开关门时间段
     * @param request
     * @param messionId
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     * @throws ParseException
     */
    @RequestMapping(value = "/getMessionOpenByMessionNumber", method=RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getMessionOpenByMessionNumber(HttpServletRequest request, String messionId,String carNumber) throws UnsupportedEncodingException, UnknownHostException, ParseException {


        Mession mession = messionDao.findMessionByMessionNumberAndCarNumber(messionId,carNumber);

//        Mession mession = messionDao.findMessionByMessionNumber(messionId);


        JSONObject object = new JSONObject();
        String d = "yyyy-MM-dd HH:mm:ss";
        object.put("startOpenTime",DateTool.Date2String(mession.getStartOpenDoorTime(),d).split(" ")[1]);
        object.put("startCloseTime",DateTool.Date2String(mession.getStartCloseDoorTime(),d).split(" ")[1]);
        object.put("endOpenTime",DateTool.Date2String(mession.getEndOpenDoorTime(),d).split(" ")[1]);
        object.put("endCloseTime",DateTool.Date2String(mession.getEndCloseDoorTime(),d).split(" ")[1]);

        object.put("endPlus",getDistanceTime(DateTool.Date2String(mession.getStartCloseDoorTime(),"yyyy-MM-dd HH:mm:ss"),DateTool.Date2String(mession.getStartOpenDoorTime(),"yyyy-MM-dd HH:mm:ss")));
        object.put("startPlus",getDistanceTime(DateTool.Date2String(mession.getEndCloseDoorTime(),"yyyy-MM-dd HH:mm:ss"),DateTool.Date2String(mession.getEndOpenDoorTime(),"yyyy-MM-dd HH:mm:ss")));

        return object.toString();
    }



    public static String timePlus(Date time1,Date time2) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        java.util.Date now = df.parse(DateTool.Date2String(time1,"yyyy-MM-dd HH:mm:ss"));

        java.util.Date date=df.parse(DateTool.Date2String(time2,"yyyy-MM-dd HH:mm:ss"));

        long l=now.getTime()-date.getTime();

        long day=l/(24*60*60*1000);

        long hour=(l/(60*60*1000)-day*24);

        long min=((l/(60*1000))-day*24*60-hour*60);

        long s=(l/1000-day*24*60*60-hour*60*60-min*60);

        String smin = "";
        String ss = "";

        if(min < 10)
        {
            smin = "0"+min;
        }
        else
        {
            smin = String.valueOf(min);
        }

        if(s < 10)
        {
            ss = "0"+s;
        }
        else
        {
            ss = String.valueOf(s);
        }

        String times = smin+":"+ss;

//        System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");

        return times;
    }




    public static String getDistanceTime(String str1, String str2) throws ParseException {
       /* DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day + "天" + hour + "小时" + min + "分" + sec + "秒";*/
/*        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long[] times = {day, hour, min, sec};
        String m = String.valueOf(min)+"分";
        return m;*/
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        one = df.parse(str1);
        two = df.parse(str2);
        long time1 = one.getTime();
        long time2 = two.getTime();
        long diff ;
        int minutes = 0;
        if(time1<time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }

        minutes = (int) (diff/(1000 * 60));

        return String.valueOf(minutes)+"分钟";
//        return min;
    }


    public static String getFirstAndLastOfWeek(String dataStr) throws ParseException {
        Calendar cal = Calendar.getInstance();

        cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(dataStr));

        int d = 0;
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            d = -6;
        } else {
            d = 2 - cal.get(Calendar.DAY_OF_WEEK);
        }
        cal.add(Calendar.DAY_OF_WEEK, d);
        // 所在周开始日期
        String data1 = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        // 所在周结束日期
        String data2 = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return data1 + "=" + data2;

    }

    public static String getFirstAndLastOfMonth() throws ParseException {
        LocalDate today = LocalDate.now();
        //本月的第一天
        LocalDate firstday = LocalDate.of(today.getYear(),today.getMonth(),1);
        //本月的最后一天
        LocalDate lastDay =today.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("本月的第一天"+firstday);
        System.out.println("本月的最后一天"+lastDay);

        return firstday + "=" + lastDay;

    }


}
